package org.example.likou150.stack;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

//https://leetcode.cn/problems/simplify-path/?envType=study-plan-v2&envId=top-interview-150
public class SimplifyPath {
    public static void main(String[] args) {
        SimplifyPath simplifyPath=new SimplifyPath();
        System.out.println(simplifyPath.simplifyPath("/../"));
//        "/home//foo/"
    }

    public String simplifyPath(String path) {
        String[] split = path.split("/");
        Deque<String> stack=new LinkedList<>();
        for (int i = 0; i < split.length; i++) {
            // 1.多个if判断可以看看是否能合并
            if("..".equals(split[i])){
                if(!stack.isEmpty()){
                    stack.pop();
                }
            }else if(!("".equals(split[i]) || ".".equals(split[i]))) {
                stack.push(split[i]);
            }
        }
        StringBuilder result = new StringBuilder();
        if(stack.isEmpty()){
            return "/";
        }else {
            while(!stack.isEmpty()){
                result.append("/");
                // 2. 直接弹出最后一个值，效率要更好
                result.append(stack.pollLast());
            }
        }
    return result.toString();
    }
}
